package com.yjhb.android.sbz.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.EverydayMoneyActivity;
import com.yjhb.android.sbz.activity.EverydayWelfareActivity;
import com.yjhb.android.sbz.activity.MsgNoticeActivity;
import com.yjhb.android.sbz.activity.NewcomerWelfareActivity;
import com.yjhb.android.sbz.activity.SystemAnnouncementActivity;
import com.yjhb.android.sbz.activity.VipCenterActivity;
import com.yjhb.android.sbz.adapter.TopRecomAdapter;
import com.yjhb.android.sbz.dialog.TipsDialog;
import com.yjhb.android.sbz.entity.AdBanner;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.entity.RedPackDetails;
import com.yjhb.android.sbz.entity.SystemAnnouncement;
import com.yjhb.android.sbz.entity.Task;
import com.yjhb.android.sbz.entity.TaskInfo;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.mvp.home.HomePresenter;
import com.yjhb.android.sbz.mvp.home.HomeView;
import com.yjhb.android.sbz.tool.AnimationTool;
import com.yjhb.android.sbz.tool.DataSaveTool;
import com.yjhb.android.sbz.tool.LoadingDialogTool;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.v2.activity.PromotionRewardActivityV2;
import com.yjhb.android.sbz.v2.activity.UserRewardActivityV2;
import com.yjhb.android.sbz.v2.activity.V2InviteFriendActivity;
import com.yjhb.android.sbz.v2.dialog.NewUserDialog;
import com.yjhb.android.sbz.v2.mvp.presenter.NowPresenter;
import com.yjhb.android.sbz.v2.mvp.presenter.V2HomePresenter;
import com.yjhb.android.sbz.v2.mvp.view.NowView;
import com.yjhb.android.sbz.v2.mvp.view.V2HomeView;
import com.jojo.android.zxlib.base.BaseFragment;
import com.jojo.android.zxlib.base.BaseRecyclerAdapter;
import com.jojo.android.zxlib.base.BaseRecyclerAdapterV2;
import com.jojo.android.zxlib.tool.Global;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxSpanTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.view.CircleImageView;
import com.jojo.android.zxlib.view.EmptyRecyclerView;
import com.jojo.android.zxlib.view.dialog.ILoading;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.tencent.qcloud.tim.uikit.Observer;
import com.tencent.qcloud.tim.uikit.UnReadManager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.loader.ImageLoaderInterface;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * 创建者 zx
 * 创建时间 2020/11/19 17:07
 */
public class HomeFragment extends BaseFragment<HomePresenter> implements HomeView, SwipeRefreshLayout.OnRefreshListener, BaseRecyclerAdapter.ItemClickListener<TaskInfo>, Observer<Integer>, V2HomeView, NowView {
    private final String TAG = "HomeFragment";

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;

    @BindView(R.id.textSwitcher)
    TextSwitcher textSwitcher;
    @BindView(R.id.recommendListView)
    EmptyRecyclerView recommendListView;
    @BindView(R.id.quickReviewListView)
    EmptyRecyclerView quickReviewListView;

    @BindView(R.id.recommend_iv)
    ImageView recommendIv;
    @BindView(R.id.recommend_tv)
    TextView recommendTv;
    @BindView(R.id.recommend_ll)
    LinearLayout recommendLl;
    @BindView(R.id.rapidly_check_iv)
    ImageView rapidlyCheckIv;
    @BindView(R.id.rapidly_check_tv)
    TextView rapidlyCheckTv;
    @BindView(R.id.rapidly_check_ll)
    LinearLayout rapidlyCheckLl;
    @BindView(R.id.unread_tv)
    TextView unreadTv;
    @BindView(R.id.msgView)
    FrameLayout msgView;
    @BindView(R.id.recommend_line)
    View recommendLine;
    @BindView(R.id.rapidly_check_line)
    View rapidlyCheckLine;
    @BindView(R.id.home_banner)
    Banner home_banner;
    @BindView(R.id.newcomer_iv)
    ImageView newcomer_iv;
    @BindView(R.id.tag_iv)
    ImageView tag_iv;
    @BindView(R.id.what_iv)
    ImageView what_iv;
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinator;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.makeMoneyView)
    FrameLayout makeMoneyView;
    @BindView(R.id.make_money_iv)
    ImageView make_money_iv;

    private LinearLayout currSelected;

    TopRecomAdapter topRecomAdapter;
    List<TaskInfo> recommendTasks = new ArrayList<>();
    List<TaskInfo> quickReviewTasks = new ArrayList<>();
    List<TaskInfo> tops = new ArrayList<>();
    List<SystemAnnouncement> systemAnnouncements;
    ILoading loadingDialog;

    private Adapter recommendAdapter;
    private Adapter quickReviewAdapter;
    private int index;

    private List<AdBanner> adBanners;

    private V2HomePresenter v2HomePresenter;
    private final int fastSize = 50;
    private final int recommendSize = 50;
    private int fastCurrent = 1;
    private int recommendCurrent = 1;

    private NowPresenter nowPresenter;

    @Override
    protected HomePresenter initPresenter() {
        return new HomePresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initUI() {
        Glide.with(this).load(R.mipmap.new_welfare).into(newcomer_iv);
        Glide.with(this).load(R.mipmap.tag).into(tag_iv);
        swipeRefreshLayout.setColorSchemeColors(
                getResources().getColor(R.color.colorPrimary),
                getResources().getColor(R.color.colorPrimaryDark),
                getResources().getColor(R.color.colorPrimaryOther)
        );

        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerView.setAdapter(topRecomAdapter = new TopRecomAdapter(getContext()));
        topRecomAdapter.setData(tops);
        loadingDialog = LoadingDialogTool.createDialog(this);
        loadingDialog.setTipsText("正在加载..");
        recommendAdapter = new Adapter(getContext());
        recommendAdapter.setData(recommendTasks);
        recommendListView.setAdapter(recommendAdapter);
        quickReviewAdapter = new Adapter(getContext());
        quickReviewAdapter.setData(quickReviewTasks);
        quickReviewListView.setAdapter(quickReviewAdapter);
        noticeInit();
        noticeRoll();
        v2HomePresenter = new V2HomePresenter(this);
        nowPresenter = new NowPresenter(this);
    }


    @Override
    protected void initEvent() {
        swipeRefreshLayout.setOnRefreshListener(this);
        topRecomAdapter.setOnItemClick(this);
        EventBus.getDefault().register(this);
        UnReadManager.getInstance().register(this);
        //通过偏移量解决滑动冲突
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                swipeRefreshLayout.setEnabled(i >= 0);
            }
        });
        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
//                if (currSelected == recommendLl) {
//                    recommendCurrent++;
//                    v2HomePresenter.getRecommendList(recommendCurrent, recommendSize);
//                } else {
//                    fastCurrent++;
//                    v2HomePresenter.getFastList(fastCurrent, fastSize);
//                }
            }
        });
        recommendListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                int i = recommendListView.getLinearLayoutManager().findLastVisibleItemPosition();
                i = recommendTasks.size() - i;
                //剩余数据条数小于30条时开始预加载
                if (i > 0 && i < 30 && recommendCurrent <= recommendTasks.size() / recommendSize) {
                    recommendCurrent++;
                    v2HomePresenter.getRecommendList(recommendCurrent, recommendSize);
                }
            }
        });
        quickReviewListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                int i = quickReviewListView.getLinearLayoutManager().findLastVisibleItemPosition();
//                ZxLogTool.e("最后可见的视图索引", i);
                i = quickReviewTasks.size() - i;
//                ZxLogTool.e("剩余未浏览数据条数", i);
                //剩余数据条数小于30条时开始预加载
                if (i > 0 && i < 30 && fastCurrent <= quickReviewTasks.size() / fastSize) {
                    fastCurrent++;
//                    ZxLogTool.e("开始加载数据", fastCurrent);
                    v2HomePresenter.getFastList(fastCurrent, fastSize);
                }
            }
        });
    }


    /**
     * 按钮动画
     */
    private void btnAnim() {
        ScaleAnimation scaleAnimation1 = new ScaleAnimation(0.9f, 1.1f, 0.9f, 1.1f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);

        scaleAnimation1.setDuration(1000);
        //重复缩放
        scaleAnimation1.setRepeatMode(Animation.REVERSE);
        //无限循环
        scaleAnimation1.setRepeatCount(-1);
        if (makeMoneyView != null) {
            makeMoneyView.setAnimation(scaleAnimation1);
        }
        scaleAnimation1.start();
    }



    @Override
    protected void initData() {
//        presenter.getHomeTops();
        presenter.getBanner();
        presenter.getSystemNotice();
        selected(recommendLl);
    }

    @Override
    public void onRefresh() {
//        presenter.getHomeTops();
        presenter.getSystemNotice();
        presenter.getBanner();
        recommendCurrent = 1;
        fastCurrent = 1;
        if (currSelected == recommendLl) {
            v2HomePresenter.getRecommendList(recommendCurrent, recommendSize);
        } else {
            v2HomePresenter.getFastList(fastCurrent, fastSize);
        }

    }


    private void newUserDialog() {
        if (App.userInfo != null) {
            long time = System.currentTimeMillis() - App.userInfo.getCreateTime().getTime();
            if (time > 0 && time < 7 * 24 * 1000 * 60 * 60) {
                if (DataSaveTool.getShowNewUserCount() < 3) {
                    NewUserDialog newUserDialog = new NewUserDialog(getActivity());
                    newUserDialog.show();
                    DataSaveTool.addShowNewUserCount();
                }

            }

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsg(EventMsg msg) {
        try {
            if (msg.msg == EventMsg.HOME_TOP_REFRESH) {
                CoordinatorLayout.Behavior behavior =
                        ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).getBehavior();
                if (behavior instanceof AppBarLayout.Behavior) {
                    AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
                    int topAndBottomOffset = appBarLayoutBehavior.getTopAndBottomOffset();
                    if (topAndBottomOffset != 0) {
                        appBarLayoutBehavior.setTopAndBottomOffset(0);
                    }
                }
                recommendListView.getLinearLayoutManager().scrollToPositionWithOffset(0, 0);
                quickReviewListView.getLinearLayoutManager().scrollToPositionWithOffset(0, 0);
                swipeRefreshLayout.setRefreshing(true);
                onRefresh();
            }else if (msg.msg == EventMsg.LOGIN_SUCCESS){
                newUserDialog();
            }
        } catch (Exception e) {
            ZxLogTool.err(e);
        }

    }

    @Override
    public void update(int type, Integer arg) {
        int totalUnread = UnReadManager.getInstance().getUnreadMsg()
                + UnReadManager.getInstance().getUncheck()
                + UnReadManager.getInstance().getUnreadSys()
                + UnReadManager.getInstance().getUnreadTask()
                + UnReadManager.getInstance().getUnreadReport();
        if (totalUnread > 0) {
            msgView.setVisibility(View.VISIBLE);
            unreadTv.setVisibility(View.VISIBLE);
            unreadTv.setText("" + totalUnread);
        } else {
            msgView.setVisibility(View.VISIBLE);
            unreadTv.setVisibility(View.GONE);
            unreadTv.setText("");
        }
    }

    @OnClick(R.id.msgView)
    void msgView() {
//        ZxToast.showINFOBottomToast("功能开发中...");
//        return;
        if (Tool.checkLogin(getContext())) {
            ZxActivityTool.skipActivity(getContext(), MsgNoticeActivity.class);
        }
    }

    @Override
    public void onDestroy() {
        UnReadManager.getInstance().unregister(this);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void selected(LinearLayout linearLayout) {
        currSelected = linearLayout;
        if (linearLayout == recommendLl) {
            what_iv.setVisibility(View.INVISIBLE);
            rapidlyCheckIv.getDrawable().setTint(Color.BLACK);
            rapidlyCheckTv.setTextColor(Color.BLACK);
            recommendIv.getDrawable().setTint(0xFFFF4266);
            recommendTv.setTextColor(0xFFFF4266);
            recommendLine.setVisibility(View.VISIBLE);
            rapidlyCheckLine.setVisibility(View.INVISIBLE);
            loadingDialog.show();
            selectedList(recommendListView);
            recommendCurrent = 1;
            v2HomePresenter.getRecommendList(recommendCurrent, recommendSize);

        } else if (linearLayout == rapidlyCheckLl) {
            what_iv.setVisibility(View.VISIBLE);
            recommendIv.getDrawable().setTint(Color.BLACK);
            recommendTv.setTextColor(Color.BLACK);
            rapidlyCheckIv.getDrawable().setTint(0xFFFF4266);
            rapidlyCheckTv.setTextColor(0xFFFF4266);
            recommendLine.setVisibility(View.INVISIBLE);
            rapidlyCheckLine.setVisibility(View.VISIBLE);
            loadingDialog.show();
            selectedList(quickReviewListView);
            fastCurrent = 1;
            v2HomePresenter.getFastList(fastCurrent, fastSize);
            //第一次点击快审展示提示弹窗
            if (DataSaveTool.isRapidlyCheckTips()) {
                Global.getInstance().getMainHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showRapidlyCheckTips();
                    }
                }, 1500);
            }
        }

    }

    private void selectedList(EmptyRecyclerView lowListView) {
        if (lowListView == quickReviewListView) {
            quickReviewListView.setVisibility(View.VISIBLE);
            recommendListView.setVisibility(View.GONE);
        } else {
            recommendListView.setVisibility(View.VISIBLE);
            quickReviewListView.setVisibility(View.GONE);
        }
    }

    private void showRapidlyCheckTips() {
        CharSequence charSequence = "极速快审板块内的任务，悬赏主会在您提交数据后的1小时内审核，" +
                "若悬赏主超过1个小时未审核，系统将自动判断合格通过。快来试试极速快审板块的任务吧！";
        String highlight = "1小时内";
        int index = charSequence.toString().indexOf(highlight);
        TipsDialog tipsDialog = new TipsDialog(getContext());
        tipsDialog.setTitle("小提示");
        tipsDialog.setContent(ZxSpanTool.ColorSpan(charSequence, index, index + highlight.length(), Color.RED));
        tipsDialog.setSubmitText("我知道啦");
        tipsDialog.setButtonVisibility(TipsDialog.TYPE_CANCEL, View.GONE);
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.dismiss();
                DataSaveTool.saveRapidlyCheckTips(false);
            }
        });
        tipsDialog.show();
    }


    /**
     * 初始化通知动画
     */
    private void noticeInit() {
        textSwitcher.setInAnimation(AnimationTool.getInAnim());
        textSwitcher.setOutAnimation(AnimationTool.getOutAnim());
    }

    /**
     * 滚动通知
     */
    private void noticeRoll() {
        Observable.interval(5, 5, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (textSwitcher != null) {
                            if (systemAnnouncements != null && systemAnnouncements.size() > 0) {
                                if (index < systemAnnouncements.size() - 1) {
                                    index++;
                                } else {
                                    index = 0;
                                }
                                textSwitcher.setText(systemAnnouncements.get(index).getMessage());
                            } else {
                                textSwitcher.setText("");
                            }
                        }
                    }
                });
    }

    /**
     * 初始化广告位
     */
    private void initBanner() {
        home_banner.setImages(adBanners);
        home_banner.setImageLoader(new ImageLoaderInterface() {
            @Override
            public void displayImage(Context context, Object path, View imageView) {
                if (path instanceof Integer) {
                    //占满、不剪切
                    ((ImageView) imageView).setScaleType(ImageView.ScaleType.FIT_XY);
                    ((ImageView) imageView).setImageResource((Integer) path);
                } else if (path instanceof AdBanner) {
                    Glide.with(context).load(((AdBanner) path).getBanner())
                            .into((ImageView) imageView);
                }
            }

            @Override
            public View createImageView(Context context) {
                ImageView img = new ImageView(context);
                img.setScaleType(ImageView.ScaleType.FIT_XY);
                return img;
            }
        });
        home_banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);  //设置banner样式
        home_banner.setBannerAnimation(Transformer.ZoomIn); //设置banner动画效果
        home_banner.setDelayTime(1000 * 5);
        home_banner.setIndicatorGravity(BannerConfig.CENTER);
        home_banner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                position = position - 1;
                if (adBanners != null && adBanners.size() > position) {
                    AdBanner adBanner = adBanners.get(position);
                    //type ==0 跳网页  type == 1 跳APP页面 type == 2 不做操作
                    if (adBanner.getType() == 0) {
                        Tool.startWebActivity(getContext(), adBanner.getContent(), adBanner.getTitle());
                    } else if (adBanner.getType() == 1) {
                        if (!TextUtils.isEmpty(adBanner.getContent())) {
                            switch (adBanner.getContent()) {
                                case "推广奖励":
                                    ZxActivityTool.skipActivity(getContext(), PromotionRewardActivityV2.class);
                                    break;
                                case "赚":
                                    ZxActivityTool.skipActivity(getContext(), V2InviteFriendActivity.class);
                                    break;
                                case "任务大奖":
                                    ZxActivityTool.skipActivity(getContext(), UserRewardActivityV2.class);
                                    break;
                                case "游戏":
                                    EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_MAIN_SWITCH_FRAGMENT, 3));
                                    break;
                                case "会员":
                                    startActivity(new Intent(getContext(), VipCenterActivity.class));
                                    break;
                            }
                        }
                    }
                }

            }
        });
        home_banner.start();
    }


    @OnClick({R.id.recommend_ll, R.id.rapidly_check_ll})
    void onClickSelect(LinearLayout linearLayout) {
        selected(linearLayout);
    }

    @OnClick(R.id.new_user_task)
    void new_user_task() {
//        startActivity(new Intent(getContext(), NewUserTaskListActivity.class));
//        ZxActivityTool.skipActivity(getContext(), LastIssueRankActivity.class);
        ZxActivityTool.skipActivity(getContext(), UserRewardActivityV2.class);
    }

    @OnClick(R.id.makeMoneyView)
    void makeMoneyView() {
        if (Tool.checkLogin(getContext())){
            nowPresenter.getNowTask();
        }
    }

    @OnClick(R.id.newcomer)
    void newcomer() {
        startActivity(new Intent(getContext(), NewcomerWelfareActivity.class));
//        startActivity(new Intent(getContext(), TestActivity.class));
    }

    @OnClick(R.id.everyday_money)
    void everyday_money() {
        startActivity(new Intent(getContext(), EverydayMoneyActivity.class));
    }

//    @OnClick(R.id.forward_tv)
//    void forward_tv() {
//        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_MAIN_SWITCH_FRAGMENT, 1));
//    }

    @OnClick(R.id.dailySign)
    void dailySign() {
//        ZxActivityTool.skipActivity(getContext(), DailySignActivity.class);
        ZxActivityTool.skipActivity(getContext(), EverydayWelfareActivity.class);
    }

    @OnClick(R.id.promotionReward)
    void promotionReward() {
//        ZxActivityTool.skipActivity(getContext(), PromotionRewardActivity.class);
        ZxActivityTool.skipActivity(getContext(), PromotionRewardActivityV2.class);
    }

    @OnClick(R.id.sysNotice)
    void sysNotice() {
        ZxActivityTool.skipActivity(getContext(), SystemAnnouncementActivity.class);
    }

    @OnClick(R.id.what_iv)
    void what_iv() {
        CharSequence charSequence = "推荐悬赏：平台推荐的具备实力的悬赏主的优质单子。\n" +
                "极速快审：早上08:00-晚上23:00期间提交的单子不会超过1个小时审核，超时自动通过，其余报名时间超时不会计入。";
        String highLight = "推荐悬赏：";
        String highLight1 = "极速快审：";
        int index = charSequence.toString().indexOf(highLight);
        int index1 = charSequence.toString().indexOf(highLight1);
        charSequence = ZxSpanTool.ColorSpan(charSequence, index, index + highLight.length(), ResManager.getThemeColor());
        charSequence = ZxSpanTool.ColorSpan(charSequence, index1, index1 + highLight1.length(), ResManager.getThemeColor());
        TipsDialog tipsDialog = new TipsDialog(getContext());
        tipsDialog.setTitle("说明");
        tipsDialog.setContent(charSequence);
        tipsDialog.setButtonVisibility(TipsDialog.TYPE_CANCEL, View.GONE);
        tipsDialog.setSubmitText("我知道了");
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.dismiss();
            }
        });
        tipsDialog.show();
    }

    @Override
    public void onWait(String tips) {

    }

    @Override
    public void onLoadSuccess(@NotNull ArrayList<Task> data) {
        if (data.size() > 0) {
            Tool.startEditTaskDetailActivity(getContext(), data.get(0).getId(), data);
        }
    }


    @Override
    public void onRecommendList(@NotNull List<? extends TaskInfo> tasks, boolean isRefresh) {
        if (loadingDialog != null) {
            loadingDialog.cancel();
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (isRefresh) {
            this.recommendTasks.clear();
        }
        this.recommendTasks.addAll(tasks);
        if (quickReviewAdapter != null) {
            recommendAdapter.notifyDataSetChanged();
        }
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onFastList(@NotNull List<? extends TaskInfo> tasks, boolean isRefresh) {
        if (loadingDialog != null) {
            loadingDialog.cancel();
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (isRefresh) {
            this.quickReviewTasks.clear();
        }
        this.quickReviewTasks.addAll(tasks);
        if (quickReviewAdapter != null) {
            quickReviewAdapter.notifyDataSetChanged();
        }
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishLoadmore();
        }
    }


    @Override
    public void onRedPackDetail(RedPackDetails redPackDetails) {
        loadingDialog.cancel();
        Tool.startRedDetail(getContext(), redPackDetails);
    }

    @Override
    public void onBanner(List<AdBanner> adBanners) {
        this.adBanners = adBanners;
        initBanner();
    }


    @Override
    public void onTops(List<TaskInfo> tasks) {
        this.tops.clear();
        this.tops.addAll(tasks);
        topRecomAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSysNotice(List<SystemAnnouncement> systemAnnouncements) {
        this.systemAnnouncements = systemAnnouncements;
    }

    @Override
    public void onFailure(int code, String msg) {
        if (loadingDialog != null) {
            loadingDialog.cancel();
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (code != -1)
            ZxToast.showFAILBottomToast(msg);
    }


    @Override
    public void onItemClick(int index, TaskInfo task) {
        Tool.startEditTaskDetailActivity(getActivity(), task.getId());
    }

    @Override
    public void onViewClick(View view, String msg, int index, TaskInfo task) {

    }


    class Adapter extends BaseRecyclerAdapterV2<BaseRecyclerAdapterV2.BaseHolder, TaskInfo> {

        public Adapter(Context context) {
            super(context);
        }

        @Override
        protected BaseHolder getHolder(View v) {
            return new BaseHolder(v);
        }

        @Override
        protected int getLayoutId() {
            return R.layout.home_item_list_task;
        }

        @Override
        public void onBindViewHolder(@NonNull BaseHolder holder, int position) {
            CircleImageView head_iv = holder.findViewById(R.id.head_iv);
            TextView title_tv = holder.findViewById(R.id.title_tv);
            TextView people_num_tv = holder.findViewById(R.id.people_num_tv);
            TextView num_tv = holder.findViewById(R.id.num_tv);
            TextView money_tv = holder.findViewById(R.id.money_tv);
            TextView label1 = holder.findViewById(R.id.label1);
            TextView label2 = holder.findViewById(R.id.label2);
            ImageView vip_iv = holder.findViewById(R.id.vip_iv);
            View ding_tv = holder.findViewById(R.id.ding_tv);
            View bao_tv = holder.findViewById(R.id.bao_tv);
            View fast_iv = holder.findViewById(R.id.fast_iv);
            View red_envelop = holder.findViewById(R.id.red_envelop);
            final TaskInfo task = data.get(position);
            Glide.with(getContext()).load(task.getAvatar())
                    .apply(new RequestOptions().placeholder(R.mipmap.test_head)).into(head_iv);
            title_tv.setText(task.getTitle());
            people_num_tv.setText("" + task.getSuccess() + "人");
            num_tv.setText("" + task.getCurrentStock() + "个");
            BigDecimal bigDecimal = Tool.getPrettyNumber(task.getMoney());
            CharSequence money = "+" + bigDecimal + "元";
            money = ZxSpanTool.ZoomSpan(money, money.length() - 1, money.length(), 0.7f);
            money = ZxSpanTool.ZoomSpan(money, 0, 1, 0.7f);
            money = ZxSpanTool.StyleSpan(money, 1, money.length() - 1, Typeface.BOLD);
            money_tv.setText(money);
            label1.setText(Tool.idTransformString(task.getCategoryId()));
            label2.setText(task.getName());
            int vipLevel = task.getVipLevel();
            switch (vipLevel) {
                case 100:
                    vip_iv.setImageResource(R.mipmap.exp);
                    vip_iv.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    vip_iv.setImageResource(R.mipmap.month);
                    vip_iv.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    vip_iv.setImageResource(R.mipmap.season);
                    vip_iv.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    vip_iv.setImageResource(R.mipmap.year);
                    vip_iv.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    vip_iv.setImageResource(R.mipmap.half_year);
                    vip_iv.setVisibility(View.VISIBLE);
                    break;
                default:
                    vip_iv.setVisibility(View.GONE);
            }
            if (task.getCreditMoney() != null && task.getCreditMoney().intValue() >= 100) {
                bao_tv.setVisibility(View.VISIBLE);
            } else {
                bao_tv.setVisibility(View.GONE);
            }
            if (task.isRecommend()) {
                ding_tv.setVisibility(View.VISIBLE);
            } else {
                ding_tv.setVisibility(View.GONE);
            }
            if (task.getAuditFast() == 1) {
                fast_iv.setVisibility(View.VISIBLE);
            } else {
                fast_iv.setVisibility(View.GONE);
            }
            if (task.getRedPacket() == 1) {
                red_envelop.setVisibility(View.VISIBLE);
            } else {
                red_envelop.setVisibility(View.GONE);
            }

            red_envelop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Tool.checkLogin(context)){
                        loadingDialog.setTipsText("请稍候...");
                        presenter.queryRedPacket(task.getId());
                    }
                }
            });

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Tool.startEditTaskDetailActivity(getContext(), task.getId());
                }
            });

            if (position == data.size() - 1) {
                holder.findViewById(R.id.footer_tv).setVisibility(View.VISIBLE);
                holder.findViewById(R.id.footer_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_MAIN_SWITCH_FRAGMENT, 1));
                    }
                });
            } else {
                holder.findViewById(R.id.footer_tv).setVisibility(View.GONE);
            }
        }

    }

}
